$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'basics/bwarehouse/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true , hidden:true},
			{ label: '仓房名称', name: 'antennaName', index: 'antenna_name', width: 80 ,align:"center"}, 			
			{ label: '库房类型名称', name: 'warehouseTypeName', index: 'warehouse_type_name', width: 80 ,align:"center"},
			{ label: '库房类型id', name: 'warehouseTypeId', index: 'warehouse_type_id', width: 80 ,hidden:true},
			{ label: '仓房编号', name: 'unitCode', index: 'unit_code', width: 80 ,align:"center"},
			{ label: '所属部门', name: 'departmentName', index: 'department_name', width: 80 ,align:"center"},
			{ label: '条形码', name: 'barCode', index: 'bar_code', width: 80 ,align:"center"}, 			
			{ label: '备注', name: 'remark', index: 'remark', width: 80 , hidden:true}, 			
			{ label: '创建人', name: 'createUserId', index: 'create_user_id', width: 80 , hidden:true}, 			
			{ label: '创建时间', name: 'createTime', index: 'create_time', hidden:true ,width: 80 ,align:"center", formatter:function(value,options,row){
                return new Date(value).Format('yyyy-MM-dd HH:mm:ss');}}, 			
			{ label: '修改时间', name: 'updateTime', index: 'update_time', width: 80 ,align:"center", formatter:function(value,options,row){
                return new Date(value).Format('yyyy-MM-dd HH:mm:ss');}}, 			
			{ label: '状态', name: 'isUsed', index: 'is_used', width: 80 ,align:"center", formatter: function(value, options, row){
				return value === 1 ? 
						'<span class="label label-success" value="1">启用</span>' : 
						'<span class="label label-danger" value="0">禁用</span>';
			}}, 					
			{ label: '是否启用，0未启用，1启用', name: 'isUsed', index: 'is_used', width: 80 , hidden:true},
			{ label: '是否删除，1已删除，0未删除', name: 'isDel', index: 'is_del', width: 80 , hidden:true}			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "warehouseList.list",
            page: "warehouseList.pageNum",
            total: "warehouseList.pages",
            records: "warehouseList.total"
        },
        prmNames : {
            page:"page",
            rows:"limit", 
            order: "order",
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        bWarehouseTypeList:[],
		title: null,
		bWarehouse: {},//对象
		search:{//查询条件
            antennaName:'',
            unitCode:'',
            departmentId:'',
		},
        isShow:false,//是否只读
		list:[],//部门数组
		deptId:'',//当前用户部门id
        ruleValidate:{//验证
            antennaName: [{ required: true,trigger: 'blur',message:'请输入仓房名称！'}],
            departmentId: [{required: true,type:'array', trigger: 'change',message:'请输入部门名称！'}],
            warehouseTypeId: [{required: true,type:'number', trigger: 'change',message:'请选择仓房类型！'}],
        },
		isUsed:true,//是否有效 默认有效

	},

	mounted:function(){
		this.getDeptTree();
		//JsBarcode("#barcode1", "Hi world!");
	},
	methods: {
		getDeptTree:function(){

			var url="/sys/dept/getDeptTree"
			$.ajax({
				type: "get",
				url: baseURL + url,
				success: function(r){
					if(r.code === 0){
						vm.list=r.data;
						vm.deptId=r.data.length>0?r.data[0].deptId:'';
					}else{
						alert(r.msg);
					}
				}
			});
		},
		print:function(){
			var id = getSelectedRow();
			vm.bWarehouse=getRowData(id);
			if(id == null){
				return ;
			}

			JsBarcode("#barcode1", vm.bWarehouse.unitCode);
			$("#antennaName").text(vm.bWarehouse.antennaName)
			$("#unitCode").text(vm.bWarehouse.unitCode)
			$("#departmentName").text(vm.bWarehouse.departmentName)
			$("#print").print({
				//Use Global styles
				globalStyles : true,
				//Add link with attrbute media=print
				mediaPrint : false,
				//Print in a hidden iframe
				iframe : true,
				//Don't print this
				noPrintSelector : ".avoid-this",
				//Add this at top
				prepend : "",
				//Add this on bottom
				append : "",
				//Log to console when printing is done via a deffered callback
				deferred: $.Deferred().done(function() { console.log('Printing done', arguments); })
			});

		},
        selectChange:function(selVal){
            this.$forceUpdate()
        },
        getWarehouseType:function(){
            $.get(baseURL + "basics/bwarehousetype/list?limit=0&page=1000",function(r){
                vm.bWarehouseTypeList = r.warehouseTypeList.list;
            });
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bWarehouse = {};
			vm.bWarehouse.departmentId=[];
            vm.bWarehouse.departmentId.push(vm.deptId)//初始化部门
			vm.isShow=false;//可读
            vm.bWarehouse.isUsed=1;//默认有效
			vm.isUsed=true;//默认有效
            this.$refs['bWarehouse'].resetFields();
            vm.getWarehouseType();
		},
		update: function (event) {

			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
            /*this.$Spin.show({
                render:function h() {
                    return h('div', [
                        h('Icon', {
                            'class': 'demo-spin-icon-load',
                            props: {
                                type: 'ios-loading',
                                size: 18
                            }
                        }),
                        h('div', 'Loading')
                    ])
                }
            });*/
            this.$refs['bWarehouse'].validate(function(valid){
            	console.log(valid)
                if(valid) {
                	vm.bWarehouse.isUsed=vm.isUsed?1:0;
                    //部门id去最后一条
                    var departmentId = vm.bWarehouse.departmentId == '' || vm.bWarehouse.departmentId == null || vm.bWarehouse.departmentId == [] ? "" :
                        vm.bWarehouse.departmentId[vm.bWarehouse.departmentId.length - 1]
                    vm.bWarehouse.departmentId = departmentId;

                    var url = vm.bWarehouse.id == null ? "basics/bwarehouse/save" : "basics/bwarehouse/update";
                    var param = {
                        "warehouse": vm.bWarehouse
                    };

                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(param),
                        success: function (r) {
                            //vm.$Spin.hide();
                            if (r.code === 0) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                }else{
					//vm.$Spin.hide();
				}
            })

		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "basics/bwarehouse/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							var msg=r.data.msg;
							alert(msg, function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			if(vm.title=='详情'){
                vm.isShow=true;
			}else{
                vm.isShow=false;
			}
            vm.getWarehouseType();

			$.get(baseURL + "basics/bwarehouse/info/"+id, function(r){
                vm.bWarehouse = r.map.warehouse;
                vm.bWarehouse.departmentId=r.map.warehouse.departmentId.split(",")
				vm.isUsed=vm.bWarehouse.isUsed ==1;
                vm.$refs['bWarehouse'].resetFields();
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page')
			var departmentId=vm.search.departmentId==''||vm.search.departmentId==null||vm.search.departmentId==[]?"":
							vm.search.departmentId[vm.search.departmentId.length-1]
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
				postData:{
					antennaName:vm.search.antennaName,
					unitCode:vm.search.unitCode,
					departmentId:departmentId,
				},
			}).trigger("reloadGrid");
		},
		reset:function(event) {
			vm.search = {
				antennaName: '',
				unitCode: '',
				departmentId: ''
			}
			vm.reload();
		},
		detail:function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
			vm.showAdd = false;
		    vm.title = "详情";
		        
		    vm.getInfo(id);

		},
        changeUsed:function(){
            vm.bWarehouse.isUsed=vm.isUsed?1:0;
        }
	}
});

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}